package com.hxzy.facade.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.hxzy.framework.common.constant.AuthConstant;
import com.hxzy.framework.common.constant.RedisConstant;
import com.hxzy.framework.common.exception.ApiException;
import com.hxzy.framework.common.resp.R;
import com.hxzy.framework.common.resp.ResultCode;
import com.hxzy.framework.common.resp.UserDto;
import com.hxzy.framework.web.util.WebFrameworkUtils;
import com.hxzy.module.admin.api.AdminFeignApi;
import com.hxzy.module.admin.api.account.req.AccountListReq;
import com.hxzy.module.admin.api.account.resp.AdminAccountListResp;
import com.hxzy.module.admin.api.account.resp.LoadUserResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author wy
 * @Description TODO
 * @Date 2024/1/28 15:22
 * @Version 1.0
 */
@RestController
@Api(tags = "总店后台-账户管理")
@Log4j2
@RequestMapping("/account")
public class AdminAccountController {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AdminFeignApi adminFeignApi;

    @ApiOperation(value = "获取当前用户信息(菜单权限)", notes = "获取当前用户信息")
    @PostMapping(value = "/loadUser")
    public R<LoadUserResp> loadUser() {
        String token = WebFrameworkUtils.getRequest().getHeader(AuthConstant.JWT_TOKEN_HEADER);
        UserDto backUserInfo = getRedisCacheByToken(token);
        return this.adminFeignApi.adminAccountLoadUser(backUserInfo.getId());
    }

    private UserDto getRedisCacheByToken(String token){
        if (StrUtil.isBlank(token)){
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        String  key= RedisConstant.REQUEST_USER_INFO +token;
        Object redisValue = this.redisTemplate.opsForValue().get(key);
        if(Objects.isNull(redisValue)){
            throw new ApiException(ResultCode.FORBIDDEN);
        }
        //续时用 (过期-当前时 <30分钟 才做操作)
        redisTemplate.expire(key,24, TimeUnit.HOURS);

        return (UserDto) redisValue;
    }


    @ApiOperation(value = "帐号列表", notes = "帐号列表")
    @GetMapping(value = "/accountList")
    public R<PageInfo<AdminAccountListResp>> accountList(@Validated  AccountListReq req) {
        return this.adminFeignApi.accountList(req);
    }

}
